package com.wzdigit.wms.raw.service.backtosap;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.wzdigit.framework.Shift;
import com.wzdigit.wms.basic.domain.basic.Sku;
import com.wzdigit.wms.basic.domain.basic.Warehouse;
import com.wzdigit.wms.basic.domain.mapping.CodeMapping;
import com.wzdigit.wms.basic.domain.mid.IfPostback;
import com.wzdigit.wms.basic.domain.transfer.GdnDtl;
import com.wzdigit.wms.basic.domain.transfer.GdnHeader;
import com.wzdigit.wms.basic.enums.writeback.BackResultEnum;
import com.wzdigit.wms.basic.enums.writeback.OtherSystemEnum;
import com.wzdigit.wms.basic.enums.writeback.TopicEnum;
import com.wzdigit.wms.basic.mapper.core.basic.SkuMapper;
import com.wzdigit.wms.basic.mapper.core.basic.WarehouseMapper;
import com.wzdigit.wms.basic.service.code.CodeMappingService;
import com.wzdigit.wms.common.entity.StatusCode;
import com.wzdigit.wms.common.utils.SapWebServiceUtil;
import com.wzdigit.wms.raw.exception.SystemException;
import com.wzdigit.wms.raw.service.mid.IfPostbackService;
import com.wzdigit.wms.web.service.common.wms2sap.ZDT_MsgHeader;
import com.wzdigit.wms.web.service.wms2sap.materialreplace.ZDT_085_Req;
import com.wzdigit.wms.web.service.wms2sap.materialreplace.ZDT_085_ReqRECORDHEAD;
import com.wzdigit.wms.web.service.wms2sap.materialreplace.ZDT_085_Rsp;
import com.wzdigit.wms.web.service.wms2sap.materialreplace.ZSI_085_WMS2SAP_OUTProxy;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/*
 * 物料替代回写
 * 
 * @author shuaic
 * @date 2021/6/18 18:44
*/
@Service
@Slf4j
public class MaterialReplaceWriteOffService {
	
    @Autowired
    private IfPostbackService ifPostbackService;

    @Autowired
    private CodeMappingService codeMappingService;

    @Autowired
    private WarehouseMapper warehouseMapper;
    
    @Autowired
    private SkuMapper skuMapper;

    @Value("${sap.web.service.protocol-head}")
    private String protocolHead;

    @Value("${sap.web.service.materialReplace-url}")
    private String uri;

    @Value("${wzdigit.web.service.sap.ip}")
    private String ip;

    /*
     * 料号转换同步回传SAP
     * 
     * @param recordhead
     * @return void
     * @author shuaic
     * @date 2021/8/10 20:07
     */
	public void backToSap(ZDT_085_ReqRECORDHEAD recordhead) throws Exception {
		log.info("调用SAP物料转换接口开始--------");
		log.info("发送的报文===》" + recordhead);
		
		String urlString = protocolHead + ip + uri;
		
		ZDT_085_Req req = new ZDT_085_Req();

		ZDT_MsgHeader header = SapWebServiceUtil.getHeader();
		req.setHEADER(header);

		ZDT_085_ReqRECORDHEAD[] records = new ZDT_085_ReqRECORDHEAD[]{recordhead};
		req.setRECORD(records);

		ZSI_085_WMS2SAP_OUTProxy proxy = new ZSI_085_WMS2SAP_OUTProxy();
		proxy.setEndpoint(urlString);
		
		ZDT_085_Rsp rsp = null;// 回参
		try {
			// 调接口
			rsp = proxy.ZSI_085_WMS2SAP_OUT(req);
			log.info("回传的报文===》" + JSON.toJSONString(rsp));
			log.info("调用SAP物料转换接口结束--------");
		} catch (Exception e) {
			log.info("调用SAP物料转换接口异常--------");
			e.printStackTrace();
			throw e;
		}
		
		if (!"S".equals(rsp.getRECORD()[0].getZSTATE())) {
			String msg = rsp.getRECORD()[0].getZMSG();
			if(StringUtils.isBlank(msg)) {
				msg = "处理失败";
			}
			throw new SystemException(String.format("SAP反馈：%s", msg));
		}
	}

    /*  
     * 交货单冲销同步GDN
     * 
     * @param header 表头
     * @param dtl 明细
     * @return boolean
     * @author shuaic
     * @date 2021/6/18 9:57
     */
	public void materialReplaceWriteBack(GdnHeader header, List<GdnDtl> dtlList) {
		// 生成回写数据
		List<ZDT_085_ReqRECORDHEAD> list = new ArrayList<>();
		for (GdnDtl dtl : dtlList) {
			ZDT_085_ReqRECORDHEAD record = new ZDT_085_ReqRECORDHEAD();
			Sku sku = skuMapper.selectById(dtl.getSkuId());
			if (sku == null) {
				String message = String.format("未找到ID为【%s】的SKU信息", dtl.getSkuId());
				Shift.fatal(StatusCode.BUSINESS_ERR, message);
			}

			// 查询仓库
			Warehouse warehouse = warehouseMapper.selectById(dtl.getWhsId());
			CodeMapping codeMapping = codeMappingService.selectByWhsCodeAndFactoryOrQaStatus(header.getFactory(),
					warehouse.getWhsCode(), 0);
			// TODO
			record.setBUDAT(DateUtil.format(header.getGdnApprovedTime(), "yyyyMMdd")); // 过帐日期
			record.setWERKS(""); // 调出工厂
			record.setLGORT(""); // 调出库位
			record.setMATNR(""); // 调出物料
			record.setMENGE(""); // 调出数量
			record.setUMMAT(""); // 调入物料
			record.setUMLGO(""); // 调入库位
			list.add(record);
		}
		String jsonString = JSON.toJSONString(list);

		// 插入数据到待回传数据表
		IfPostback ifPostback = new IfPostback();
		ifPostback.setDestSystem(OtherSystemEnum.SYSYTEM_SAP.getEnumName());
		ifPostback.setPostbackTopic(TopicEnum.TOPIC_SAP_MATERIAL_REPLACE.getEnumName());
		ifPostback.setPostbackContent(jsonString);
		ifPostback.setPostbackResult(BackResultEnum.DEFAULT_STATE.getCode());
		ifPostback.setCreateTime(new Date());
		ifPostback.setDestSystem(OtherSystemEnum.SYSYTEM_SAP.getEnumName());
		try {
			ifPostbackService.addOne(ifPostback);// 保存
		} catch (Exception e) {
			e.printStackTrace();
			Shift.fatal(StatusCode.SERVER_MODIFY_ERROR);
		}
	}
}
